///////////////////////////////////////////////////////////////////////////////
//  File:       moneyinfo.cpp
//
//  Summary:    Handles currency conversion
//
//  Sample:     CSF Headlines
//
//---------------------------------------------------------------------
//  This file is part of the Microsoft Commerce Server 2000 SDK
//
//  Copyright (C) 2000 Microsoft Corporation.  All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Commerce Server 2000 and/or on-line documentation.  See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
///////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "moneyinfo.h"

#include "resource.h" //for resources
#include "smartdict.h"

const int g_maxErrorMsgSize = 2048;

CMoneyInfo::CMoneyInfo()
{

}

int GetRoundingScale(int DecimalPlaces)
{
    switch (DecimalPlaces)
    {
        case -3: return 10000000;
        case -2: return 1000000;
        case -1: return 100000;
        case 0:  return 10000;
        case 1:  return 1000;
        case 2:  return 100;
        case 3:  return 10;
        case 4:  return 1;
        default:
            if (DecimalPlaces>4) return 1;
            else return 10000;
    }
}

HRESULT CMoneyInfo::InitCompatible(IDictionary *pdictOrder, LPCWSTR pwszCompId, IDispatch *pdispContext, BOOL bEnableConversion)
{
    HRESULT hr = S_OK;
    CSmartDict spOrder;
    CComBSTR currency_compatibility;
    int currency_decimal_places;
    int currency_lcid;
    int nLocaleDecimalPlaces;
    spOrder.Init(pdictOrder, L"orderform", L"Pipeline", pdispContext); //no returnval

    // get the currency mode (and transform to 3 or 4)
    if (FAILED(hr = spOrder.GetValueDefault(L"_currency_compatibility", L"", &currency_compatibility)))
        goto CleanUp;
    if (_wcsicmp(currency_compatibility, L"cy") != 0)
    {
        m_CurrencyMode = 3;
    }
    else
    {
        m_CurrencyMode = 4;
    }

    //NOTE: the rest of this function is the same as the lower part of Init()

    // get the number of decimal places, defaulting to 2
    if (FAILED(hr = spOrder.GetValueDefault(L"_currency_decimal_places", 2, &currency_decimal_places)))
        goto CleanUp;
    m_RoundingScale = GetRoundingScale(currency_decimal_places);

    if (m_CurrencyMode==3 || bEnableConversion)
    {
        // get the currency<->int conversion factor  (we could cache this on the orderform...)
        if (FAILED(hr = spOrder.GetValue(L"_currency_lcid", &currency_lcid)))
            goto CleanUp;
        WCHAR buf[50];
        if (!(GetLocaleInfo(currency_lcid, LOCALE_ICURRDIGITS | LOCALE_NOUSEROVERRIDE, buf, sizeof(buf))))
        {
            hr = GetLastError();
            if (!(hr & 0xFFFF0000)) hr = HRESULT_FROM_WIN32(hr);
            goto CleanUp;
        }
        nLocaleDecimalPlaces = _wtoi(buf);
        m_IntToCurrencyConversionScale = GetRoundingScale(nLocaleDecimalPlaces);
    }
    else
    {
        m_IntToCurrencyConversionScale = 0;
    }

    if (FAILED(hr = InitError(pwszCompId, pdispContext)))
        goto CleanUp;

CleanUp:
    return hr;
}

HRESULT CMoneyInfo::Init(IDispatch *pdispOrder, LPCWSTR pwszCompId, IDispatch *pdispContext, BOOL bEnableConversion)
{
    CComQIPtr<IDictionary> pdictOrder;
    pdictOrder = pdispOrder;
    if (!pdictOrder)
        return E_NOINTERFACE;
    return Init(pdictOrder, pwszCompId, pdispContext, bEnableConversion);
}


HRESULT CMoneyInfo::Init(IDictionary *pdictOrder, LPCWSTR pwszCompId, IDispatch *pdispContext, BOOL bEnableConversion)
{
    HRESULT hr = S_OK;
    CSmartDict spOrder;
    int currency_decimal_places;
    int currency_lcid;
    int nLocaleDecimalPlaces;
    spOrder.Init(pdictOrder, L"orderform", L"Pipeline", pdispContext); //no returnval

    // currency mode is always 4
    m_CurrencyMode = 4;

    //NOTE: the rest of this function is the same as the lower part of InitCompatible()

    // get the number of decimal places, defaulting to 2
    if (FAILED(hr = spOrder.GetValueDefault(L"_currency_decimal_places", 2, &currency_decimal_places)))
        goto CleanUp;
    m_RoundingScale = GetRoundingScale(currency_decimal_places);

    if (m_CurrencyMode==3 || bEnableConversion)
    {
        // get the currency<->int conversion factor  (we could cache this on the orderform...)
        if (FAILED(hr = spOrder.GetValue(L"_currency_lcid", &currency_lcid)))
            goto CleanUp;
        WCHAR buf[50];
        if (!(GetLocaleInfo(currency_lcid, LOCALE_ICURRDIGITS | LOCALE_NOUSEROVERRIDE, buf, sizeof(buf))))
        {
            hr = GetLastError();
            if (!(hr & 0xFFFF0000)) hr = HRESULT_FROM_WIN32(hr);
            goto CleanUp;
        }
        nLocaleDecimalPlaces = _wtoi(buf);
        m_IntToCurrencyConversionScale = GetRoundingScale(nLocaleDecimalPlaces);
    }
    else
    {
        m_IntToCurrencyConversionScale = 0;
    }

    if (FAILED(hr = InitError(pwszCompId, pdispContext)))
        goto CleanUp;

CleanUp:
    return hr;
}

HRESULT CMoneyInfo::InitError(LPCWSTR pwszCompId, IDispatch *pdispContext)
{
    HRESULT hr = S_OK;
    if (!(lstrcpyW(m_wszCompId, pwszCompId)))
    {
        hr = E_OUTOFMEMORY;
        goto CleanUp;
    }
    m_pdispContext = pdispContext;
CleanUp:
    return hr;
}

int CMoneyInfo::GetMode()
{
    return m_CurrencyMode;
}

HRESULT CMoneyInfo::RoundCurrency(CURRENCY in, CURRENCY &out)
{
    if(in.int64 > 0)
        in.int64 += m_RoundingScale / 2;
    else
        in.int64 -= m_RoundingScale / 2;

    out.int64 = (in.int64 / m_RoundingScale) * m_RoundingScale;
    return S_OK;
}

HRESULT CMoneyInfo::ErrOverflow(BSTR bstrKey)
{
    WCHAR errText[g_maxErrorMsgSize];

    if (bstrKey)
    {
        if (LoadString(HELPER_GETDLLINSTANCE_METHOD,
                        3 == m_CurrencyMode ? IDS_MONEY_OVERFLOW_ON_KEY_UPGRADABLE : IDS_MONEY_OVERFLOW_ON_KEY,
                        errText,
                        sizeof(errText)))
        {
            CComBSTR bstrError;
            bstrError.Attach(SysAllocStringLen(NULL, wcslen(errText) + SysStringLen(bstrKey)));
            if (bstrError)
            {
                wsprintf(bstrError, errText, bstrKey);
                AtlReportError(CLSID_CDictionary, bstrError, IID_IDictionary, 0);
            }
        }
    }
    else
    {
          if (LoadString(HELPER_GETDLLINSTANCE_METHOD,
                          3 == m_CurrencyMode ? IDS_MONEY_OVERFLOW_UPGRADABLE : IDS_MONEY_OVERFLOW,
                        errText,
                        sizeof(errText)))
        {
            AtlReportError(CLSID_CDictionary, errText, IID_IDictionary, 0);
        }
    }

    return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
}


HRESULT CMoneyInfo::CurrencyToInt(CURRENCY in, int &out32, WCHAR *ResultKey)
{
    HRESULT hr = S_OK;
    __int64 out64;

    _Assert(m_IntToCurrencyConversionScale);
    if (m_IntToCurrencyConversionScale == 0)
        E_INVALIDARG;

    if(in.int64 > 0i64)
        in.int64 += m_IntToCurrencyConversionScale / 2;  // +=.5 (so truncation emulates rounding)
    else
        in.int64 -= m_IntToCurrencyConversionScale / 2;  // -=.5

    out64 = in.int64 / m_IntToCurrencyConversionScale;

    if (out64 > 2147483647i64 || out64 < -2147483648i64)
    {
        if (FAILED(hr = ErrOverflow(ResultKey)))
            goto CleanUp;
    }

    out32 = (int) out64;

CleanUp:
    return hr;
}

HRESULT CMoneyInfo::IntToCurrency(int in, CURRENCY &out)
{
    _Assert(m_IntToCurrencyConversionScale);
    if (m_IntToCurrencyConversionScale == 0)
        return E_INVALIDARG;

    out.int64 = in * m_IntToCurrencyConversionScale;
    return S_OK;
}

HRESULT CMoneyInfo::MultiplyMoney(CURRENCY &result, const CURRENCY &cy, double mul, WCHAR *ResultKey)
{
    // This function need only check for 64-bit overflow.  32-bit overflow is handled when converting cy->int
    result.int64 = (__int64) (cy.int64 * mul);

    if ((cy.int64 >= 0 && mul >= 0) || (cy.int64 <= 0 && mul <= 0)) // pos*pos, or neg*neg -> expect positive results
    {
        if (result.int64 < 0) return ErrOverflow(ResultKey);
    }
    else   // neg*pos, or pos*neg -> expect negative results
    {
        if (result.int64 > 0) return ErrOverflow(ResultKey);
    }

    return S_OK;
}

HRESULT CMoneyInfo::AddMoney(CURRENCY &result, const CURRENCY &cy1, const CURRENCY &cy2, WCHAR *ResultKey)
{
    // This function need only check for 64-bit overflow.  32-bit overflow is handled when converting cy->int
    result.int64 = cy1.int64 + cy2.int64;

    if (cy1.int64 >= 0 && cy2.int64 >= 0) //pos+pos -> expect positive results
    {
        if (result.int64 < 0) return ErrOverflow(ResultKey);
    }
    else if (cy1.int64 <= 0 && cy2.int64 <= 0) //neg+neg -> expect negative results
    {
        if (result.int64 > 0) return ErrOverflow(ResultKey);
    }

    return S_OK;
}

HRESULT CMoneyInfo::SubtractMoney(CURRENCY &result, const CURRENCY &cy1, const CURRENCY &cy2, WCHAR *ResultKey)
{
    CURRENCY cyNegCy2;
    cyNegCy2.int64 = -cy2.int64;
    return AddMoney(result, cy1, cyNegCy2, ResultKey);
}


